﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BrightIdeasSoftware;
using FrameworkLib.Configurations.FormsConfiguration.BL;
using FrameworkLib.Configurations.FormsConfiguration.Facade;
using System.Xml;

namespace FrameworkLib.Configurations.FormsConfiguration.Extensions
{
    public static class ColumnConfigurationExtension
    {
        public static bool SaveColumnsConfiguration(this ObjectListView grid, SavingConfigurationBag savingConfigurationBag)
        {
            bool retValue = false;

            List<ColumnConfigurationBag> m_colsCnfgColl = new List<ColumnConfigurationBag>();

            foreach (OLVColumn c in grid.AllColumns)
            {
                m_colsCnfgColl.Add(new ColumnConfigurationBag()
                {
                    ColumnName = c.AspectName,
                    Index = c.Index,
                    IsVisible = c.IsVisible,
                    Width = c.Width
                });
            }

            FormsConfiguration2Facade fcf2 = new FormsConfiguration2Facade();
            string resultXML = FrameworkLib.Utilities.GenericSerializer.SerializeWithoutDeclaration<List<ColumnConfigurationBag>>(m_colsCnfgColl);

            // qui scrittura sul db
            fcf2.SaveColumnsCfg(savingConfigurationBag, resultXML);

            return retValue;
        }

        public static bool LoadColumnsConfiguration(this ObjectListView grid, SavingConfigurationBag savingConfigurationBag)
        {
            bool retValue = false;

            FormsConfiguration2Facade fcf2 = new FormsConfiguration2Facade();
            // lettura dal db...
            string data = fcf2.GetColumnsCfg(savingConfigurationBag);

            if (!string.IsNullOrWhiteSpace(data))
            {
                List<ColumnConfigurationBag> m_columnsList = FrameworkLib.Utilities.GenericSerializer.Deserialize<List<ColumnConfigurationBag>>(data);

                foreach (ColumnConfigurationBag c in m_columnsList)
                {
                    foreach (OLVColumn olvc in grid.AllColumns)
                    {
                        if (olvc.AspectName == c.ColumnName)
                        {
                            olvc.IsVisible = c.IsVisible;
                            olvc.Width = c.Width;
                            break;
                        }
                    }
                }

                grid.RebuildColumns();
            }

            return retValue;
        }
    }
}
